package parser

import (
	"GraduationProject/public/models"
	"encoding/json"
	"fmt"
	"regexp"
	"strconv"
	"time"
)

type NetEasyMusicComment struct {
	Comments []Comment `json:"comments"`
	Total    int       `json:"total"`
	More     bool      `json:"more"`
}

type Comment struct {
	User struct {
		Nickname  string `json:"nickname"`
		UserID    int    `json:"userId"`
		AvatarURL string `json:"avatarUrl"`
	} `json:"user"`
	CommentID int    `json:"commentId"`
	Content   string `json:"content"`
	Time      int64  `json:"time"`
}

type StoreComment struct {
	SongID        string `json:"song_id"`
	UserNickname  string `json:"user_nickname"`
	UserID        int    `json:"user_id"`
	UserAvatarUrl string `json:"user_avatar_url"`
	CommentID     int    `json:"comment_id"`
	Content       string `json:"content"`
	Time          string `json:"time"`
}

var urlSongIDRegex = regexp.MustCompile(`https://music.163.com/weapi/v1/resource/comments/R_SO_4_([0-9]*)\?csrf_token=(.*)`)

//url: https://music.163.com/weapi/v1/resource/comments/R_SO_4_464009018?csrf_token=
func Comments(seed models.Record, content []byte) (records []models.Record, more bool) {
	//fmt.Printf("Comments content: %s\n", content)
	songIDStrs := urlSongIDRegex.FindAllStringSubmatch(seed.Url, 1)
	var songID string
	if len(songIDStrs) < 1 {
		fmt.Println("not found songID: ", seed.Url)
		songID = seed.Url
	} else {
		songID = songIDStrs[0][1]
	}

	var netEasyMusicComment NetEasyMusicComment
	if err := json.Unmarshal(content, &netEasyMusicComment); err != nil {
		fmt.Printf("[ Comments Parser ] error: %v\n", err)
		return nil, false
	}

	if len(netEasyMusicComment.Comments) == 0 {
		return nil, false
	}

	records = make([]models.Record, len(netEasyMusicComment.Comments))
	for i, v := range netEasyMusicComment.Comments {
		records[i] = seed
		uniqueKey, _ := json.Marshal(models.Param{
			Key:   "net_easy_music_comment_unique_" + strconv.Itoa(int(seed.ID)),
			Value: strconv.Itoa(v.CommentID),
		})
		records[i].UniqueKey = string(uniqueKey)
		//result, _ := json.Marshal(v)
		result, _ := json.Marshal(StoreComment{
			SongID:        songID,
			UserNickname:  v.User.Nickname,
			UserID:        v.User.UserID,
			UserAvatarUrl: v.User.AvatarURL,
			CommentID:     v.CommentID,
			Content:       v.Content,
			Time:          time.Unix(v.Time/1000, 0).String(),
		})
		records[i].Result = string(result)
	}

	return records, netEasyMusicComment.More
}
